package com.gf.gateway.config;

import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.digest.DigestUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.security.Key;

/**
 * @ author: rui.wang@yamu.com
 * @ description: token
 * @ date: 2024/1/3
 */
@Slf4j
@Component
public class TokenProvider implements InitializingBean {

    private JwtParser jwtParser;

    private final JWTProperties jwtProperties;

    public TokenProvider(JWTProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getBase64Secret());
        Key key = Keys.hmacShaKeyFor(keyBytes);
        jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
    }

    /**
     * 验证token
     *
     * @param token token
     * @return boolean
     */
    public Claims tokenValidate(String token) {
        try {
            return getClaims(token);
        } catch (Exception e) {
            log.error("验证token异常:{}", e.getMessage());
            return null;
        }
    }

    public Claims getClaims(String token) {
        return jwtParser.parseClaimsJws(token).getBody();
    }

    /**
     * 根据身份信息获取键值
     *
     * @param claims 身份信息
     * @param key    键
     * @return 值
     */
    public String getValue(Claims claims, String key) {
        return Convert.toStr(claims.get(key), "");
    }


    /**
     * 获取登录用户RedisKey
     *
     * @param token /
     * @return key
     */
    public String loginKey(String token) {
        Claims claims = getClaims(token);
        String md5Token = DigestUtil.md5Hex(token);
        return jwtProperties.getOnlineKey() + claims.getSubject() + "-" + md5Token;
    }
}
